from datetime import datetime
from django.conf import settings
from django.shortcuts import render, HttpResponse, redirect, HttpResponsePermanentRedirect, reverse
from django.http import JsonResponse
from rbac.models import UserInfo
import pymysql
from .selfsql import SelfSql
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.clickjacking import xframe_options_exempt, xframe_options_sameorigin, xframe_options_deny
import os
import time
import json
from django.forms import Form, fields, widgets
import chardet
import re
# from rbac.middleware.rbac import

res = SelfSql()


def hello(requrst):
    """
    测试页
    :param requrst:
    :return:
    """
    return HttpResponse('hello')
    # results1 = {}
    # results1['name'] = 'Mr.Zheng'
    # return render(requrst, 'login.html', results1)


def login(request):
    """
    登陆页
    :param request:
    :return:
    """
    if request.method == "GET":
        return render(request, 'login.html')
    else:
        username = request.POST.get("username")
        pwd = request.POST.get("pwd")
        print(username, pwd)
        user_obj = UserInfo.objects.filter(name=username, password=pwd).first()

        if not user_obj:
            print("用户名或密码错误")
            return render(request, 'login.html', {'error': "用户名或密码错误"})
        else:
            permission_list = user_obj.roles.filter().values('permissions__url').distinct()
            print("访问权限：", permission_list)
            request.session['user_info'] = {'id': user_obj.id, 'name': user_obj.name}
            request.session[settings.SESSION_PERMISSION_URL_KEY] = list(permission_list)
            return redirect('/Model/')
            # return

"""
以下是六个分页
"""


def get_python(request):
    if request.method == 'GET':
        datas = res.sel_sql_news()
        return render(request, 'python.html', {'datas': datas})


def get_java(request):
    datas = [1, 2, 3, 4, 5]
    if request.method == 'GET':
        return render(request, 'java.html', {'datas': datas})


def get_c(request):
    datas = [1, 2, 3, 4, 5]
    if request.method == 'GET':
        return render(request, 'c.html', {'datas': datas})


def get_c_add(request):
    datas = [1, 2, 3, 4, 5]
    if request.method == 'GET':
        return render(request, 'c_add.html', {'datas': datas})


def get_h5(request):
    datas = [1, 2, 3, 4, 5]
    if request.method == 'GET':
        return render(request, 'h5.html', {'datas': datas})


def get_my(request):
    datas = [1, 2, 3, 4, 5]
    if request.method == 'GET':
        return render(request, 'my.html')


def get_data(request):
    datas = {}
    """
    获取数据库新闻数据
    :param request:
    :return:
    """
    datas['news'] = res.sel_sql_news()
    datas['text'] = res.sel_sql_text()

    return JsonResponse(datas)


def writer_text(request):
    """
    富文本页
    :param request:
    :return:
    """
    return render(request, 'writer_text.html')


@xframe_options_exempt
def upload_img(request):
    """
    文件上传
    :param request:
    :return:
    """

    img = request.FILES.get('post_img')
    print("图片信息：", img)
    img_dir = settings.SAVEIMG_DIRS + img.name

    with open(img_dir, 'wb')as f:
        for f_m in img.chunks():
            f.write(f_m)
    print('sava is ok !')

    dic = {
        'error': 0,
        'url': '/static/image/' + img.name,
        'message': '错误了...'
    }

    return HttpResponse(json.dumps(dic))


def save_h5(request):
    data = {}
    centext = request.body
    # 切分数据
    pattern = re.compile('(<form.*?</form>)')
    str_cen = str(centext, encoding="utf-8")
    nowtime = time.strftime("%Y%m%d%H%M%S")
    h5_dir = settings.SAVEH5_DIRS + nowtime
    htmls = str_cen.split('\n')
    # print(len(htmls))
    pattern = ['<form', '</script>']
    begin, end = 0, 0
    for i in htmls:
        if pattern[0] in i:
            begin = htmls.index(i)
        if pattern[1] in i:
            end = htmls.index(i)

    delhtml = htmls[:begin] + htmls[end:]
    delhtml = ''.join(delhtml)
    # print(delhtml)

    save_html = res.sava_html('test', nowtime, delhtml, h5_dir)
    print(save_html)

    with open(h5_dir + '.html', 'w', encoding="utf-8")as f:
        f.write(delhtml)

    if centext:
        print('收到页面信息！')
        data['message'] = "保存成功！"
    else:
        data['message'] = "保存失败！"

    return HttpResponse(json.dumps(data))


def openh5(request):
    open_dir = settings.SAVEH5_DIRS + '20200323002249.html'
    print(open_dir)
    with open(open_dir, 'r', encoding="utf-8")as f:
        datas = f.read()

    return HttpResponse(datas)


# 测试
def test_one(request):
    sel_html = res.sel_html()
    print(sel_html)
    return HttpResponse(sel_html[1][3])


# 用户中心
def User(request):
    return render(request, 'user.html')

# 模板
def Model(request):
    return render(request, 'model.html')

def Index(request):
    return render(request, 'index.html')



